package com.zzh.lib.core.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.provider.Settings;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

import com.zzh.lib.core.HLibrary;

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Locale;
import java.util.UUID;

/**
 * Created by ZZH on 2020-01-19.
 *
 * @Date: 2020-01-19
 * @Email: zzh_hz@126.com
 * @QQ: 1299234582
 * @Author: zzh
 * @Description:
 */
public class HDeviceUtils {

    protected HDeviceUtils() {
    }

    /**
     * 获取厂商名
     **/
    public static String getDeviceManufacturer() {
        return android.os.Build.MANUFACTURER;
    }

    /**
     * 获取产品名
     **/
    public static String getDeviceProduct() {
        return android.os.Build.PRODUCT;
    }

    /**
     * 获取手机品牌
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取手机型号
     */
    public static String getDeviceModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机主板名
     */
    public static String getDeviceBoard() {
        return android.os.Build.BOARD;
    }

    /**
     * 设备名
     **/
    public static String getDeviceDevice() {
        return android.os.Build.DEVICE;
    }

    /**
     * fingerprit 信息
     **/
    public static String getDeviceFubgerprint() {
        return android.os.Build.FINGERPRINT;
    }

    /**
     * 硬件名
     **/
    public static String getDeviceHardware() {
        return android.os.Build.HARDWARE;
    }

    /**
     * 主机
     **/
    public static String getDeviceHost() {
        return android.os.Build.HOST;
    }

    /**
     * 显示ID
     **/
    public static String getDeviceDisplay() {
        return android.os.Build.DISPLAY;
    }

    /**
     * build ID
     **/
    public static String getBuildId() {
        return android.os.Build.ID;
    }

    /**
     * 获取手机用户名
     **/
    public static String getDeviceUser() {
        return android.os.Build.USER;
    }

    /**
     * 获得设备序列号（如：WTK7N16923005607）, 个别设备无法获取
     *
     * @return 设备序列号
     */
    public static String getDeviceSerial() {
        try {
            return android.os.Build.getSerial();
        } catch (Exception ex) {
            return "";
        }
    }

    /**
     * 获取手机Android 系统SDK
     *
     * @return
     */
    public static int getDeviceSDK() {
        return android.os.Build.VERSION.SDK_INT;
    }

    /**
     * 获取手机Android 版本
     *
     * @return
     */
    public static String getDeviceAndroidVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取当前手机系统语言。
     */
    public static String getDeviceDefaultLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取 手机 RAM 信息 方法 一
     */
    public static String getTotalRAM() {
        ActivityManager activityManager = (ActivityManager) HLibrary.getInstance().getContext().getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(outInfo);
        long size = outInfo.totalMem;
        return Formatter.formatFileSize(HLibrary.getInstance().getContext(), size);
    }

    /**
     * 手机 RAM 信息 方法 二
     */
    public static String getTotalRAMOther() {
        String path = "/proc/meminfo";
        String firstLine = null;
        int totalRam = 0;
        try {
            FileReader fileReader = new FileReader(path);
            BufferedReader br = new BufferedReader(fileReader, 8192);
            firstLine = br.readLine().split("\\s+")[1];
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (firstLine != null) {
            Float rawFloat = Float.parseFloat(firstLine) / (1024 * 1024);
            totalRam = (int) Math.ceil((rawFloat.doubleValue()));
        }

        return Formatter.formatFileSize(HLibrary.getInstance().getContext(), totalRam);
    }

    /**
     * 获取 手机 可用 RAM
     */
    public static String getAvailableRAM() {
        ActivityManager activityManager = (ActivityManager) HLibrary.getInstance().getContext().getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(outInfo);
        long size = outInfo.availMem;
        return Formatter.formatFileSize(HLibrary.getInstance().getContext(), size);
    }

    /**
     * 是否是64位的CPU。
     *
     * @return true 是64位
     */
    public static boolean isAbi64() {
        String[] supported64BitAbis = Build.SUPPORTED_64_BIT_ABIS;
        if (supported64BitAbis != null && supported64BitAbis.length > 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取支持的CPU架构
     *
     * @return 字符串
     */
    public static String getCPUAbi() {
        return Arrays.toString(Build.SUPPORTED_ABIS);
    }

    /**
     * 判断是否是Pad
     *
     * @return true pad
     */
    public static boolean isPad() {
        return (HLibrary.getInstance().getContext().getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }


    /**
     * 默认超过7英寸的手机是PAD，主要是为了防止 isPad() 方法低分辨率的PAD上，设置大字体模式，检测的结果是手机。
     * 如果检测出来的设备是手机，则在进行一次设备屏幕尺寸检测，如果尺寸大于等于7.4 则判断为是Pad，因为手机屏幕尺寸鲜有超过7.4寸的.
     *
     * @return true 是Pad
     * @see HDeviceUtils#isPad()
     */
    public static boolean isSafePad() {
        boolean flagPhone = isPad();
        if (!flagPhone) {
            WindowManager wm = (WindowManager) HLibrary.getInstance().getContext().getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            DisplayMetrics dm = new DisplayMetrics();
            display.getMetrics(dm);
            double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
            double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
            // 屏幕尺寸
            double screenInches = Math.sqrt(x + y);
            // 大于7尺寸则为Pad
            if (screenInches >= 7.4d) {
                return true;
            }
        }
        return flagPhone;
    }

    /**
     * 是否竖屏
     *
     * @return true 竖屏
     */
    public static boolean isPortrait() {
        return HLibrary.getAppContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    /**
     * 获得设备硬件标识
     *
     * @return 设备硬件标识
     */
    public static String getDeviceId() {
        StringBuilder sbDeviceId = new StringBuilder();

        //获得AndroidId（无需权限）
        String androidid = getAndroidId();
        //获得设备序列号（无需权限）
        String serial = getDeviceSerial();
        //获得硬件uuid（根据硬件相关属性，生成uuid）（无需权限）
        String uuid = getDeviceUUID().replace("-", "");

        //追加androidid
        if (androidid != null && androidid.length() > 0) {
            sbDeviceId.append(androidid);
            sbDeviceId.append("|");
        }
        //追加serial
        if (serial != null && serial.length() > 0) {
            sbDeviceId.append(serial);
            sbDeviceId.append("|");
        }
        //追加硬件uuid
        if (uuid != null && uuid.length() > 0) {
            sbDeviceId.append(uuid);
        }
        //生成SHA1，统一DeviceId长度
        if (sbDeviceId.length() > 0) {
            try {
                byte[] hash = getHashByString(sbDeviceId.toString());
                String sha1 = bytesToHex(hash);
                if (sha1 != null && sha1.length() > 0) {
                    //返回最终的DeviceId
                    return sha1;
                }
            } catch (Exception ex) {
                LogUtils.e(ex);
            }
        }
        //如果以上硬件标识数据均无法获得，
        //则DeviceId默认使用系统随机数，这样保证DeviceId不为空
        return java.util.UUID.randomUUID().toString().replace("-", "");
    }

    private static final String[] ROM_SAMSUNG = {"samsung"};

    /**
     * Return whether the rom is made by samsung.
     *
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean isSamsung() {
        if (isRightRom(getDeviceBrand(), getDeviceManufacturer(), ROM_SAMSUNG)) {
            return true;
        }
        return false;
    }

    /**
     * 获得设备的AndroidId
     *
     * @return 设备的AndroidId
     */
    private static String getAndroidId() {
        try {
            return Settings.Secure.getString(HLibrary.getAppContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 获得设备硬件uuid
     * 使用硬件信息，计算出一个随机数
     *
     * @return 设备硬件uuid
     */
    private static String getDeviceUUID() {
        try {
            String dev = "" +
                    getDeviceBoard().length() % 10 +
                    getDeviceBrand().length() % 10 +
                    getDeviceDevice().length() % 10 +
                    getDeviceHardware().length() % 10 +
                    getBuildId().length() % 10 +
                    getDeviceModel().length() % 10 +
                    getDeviceProduct().length() % 10 +
                    getDeviceSerial().length() % 10;
            return new UUID(dev.hashCode(), getDeviceSerial().hashCode()).toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }

    /**
     * 取SHA1
     *
     * @param data 数据
     * @return 对应的hash值
     */
    private static byte[] getHashByString(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.reset();
            messageDigest.update(data.getBytes("UTF-8"));
            return messageDigest.digest();
        } catch (Exception e) {
            return "".getBytes();
        }
    }

    /**
     * 转16进制字符串
     *
     * @param data 数据
     * @return 16进制字符串
     */
    private static String bytesToHex(byte[] data) {
        StringBuilder sb = new StringBuilder();
        String stmp;
        for (int n = 0; n < data.length; n++) {
            stmp = (Integer.toHexString(data[n] & 0xFF));
            if (stmp.length() == 1)
                sb.append("0");
            sb.append(stmp);
        }
        return sb.toString().toUpperCase(Locale.CHINA);
    }

    /**
     * 是否横屏
     *
     * @return true 横屏
     */
    public static boolean isLandscape() {
        return HLibrary.getAppContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
    }

    private static boolean isRightRom(final String brand, final String manufacturer, final String... names) {
        for (String name : names) {
            if (brand.contains(name) || manufacturer.contains(name)) {
                return true;
            }
        }
        return false;
    }
}
